import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:vape_xe/routes/app_pages.dart';
import 'package:vape_xe/services/services.dart';
import 'package:vape_xe/utils/utils.dart';

class WithdrawController extends GetxController {
  /// 响应式成员变量
  final withdrawTypeList = [].obs;
  final balance = .0.obs;

  /// 成员变量
  late final TextEditingController moneyController;
  late final FocusNode focusNode;

  /// 事件
  void nextStep() {
    if (moneyController.text.isEmpty) {
      toast('Withdraw money empty'.tr);
      return;
    }
    if (double.parse(moneyController.text) > balance.value) {
      toast('${'Maximum withdraw amount'.tr}:\n${ConfigStore.to.currency} ${balance.value}');
      return;
    }
    for (var e in withdrawTypeList) {
      if (e['isSelected']) {
        Get.toNamed(Routes.WITHDRAWADDR, arguments: {
          'type': e['type'],
          'money': moneyController.text,
        });
        return;
      }
    }
  }

  void onTypeChange(int index) {
    if (withdrawTypeList[index]['isSelected'] == true) return;
    if (withdrawTypeList[index]['selectAble'] == false) {
      toast('Coming Soon'.tr);
      return;
    }
    withdrawTypeList.asMap().forEach((position, value) {
      value['isSelected'] = position == index;
    });
    withdrawTypeList.refresh();
  }

  /// 生命周期
  @override
  Future<void> onInit() async {
    super.onInit();
    moneyController = TextEditingController();
    withdrawTypeList.add({
      'icon': 'assets/images/ic_tgo.webp',
      'name': 'Touch\'n Go',
      'isSelected': true,
      'type': 3,
      'selectAble': true,
    });
    withdrawTypeList.add({
      'icon': 'assets/images/ic_usdt.webp',
      'name': 'USDT',
      'isSelected': false,
      'type': 5,
      'selectAble': false,
    });
    focusNode = FocusNode();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      focusNode.requestFocus();
    });
    await Request().get('/user/indexData').then((result) {
      balance.value = double.parse(result['result']['money']?.toString() ?? '0');
    });
  }

  @override
  void onClose() {
    focusNode.dispose();
    moneyController.dispose();
    super.onClose();
  }
}
